package org.example;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static void main(String[] args) {
        String ossUrl = "https://lf-sensitive-data.oss-cn-beijing.aliyuncs.com/0A0F000067E28C39988849DA32F91644"
                + "?Expires=1742982325"
                + "&OSSAccessKeyId=LTAI5tEnGugZbgfByLsNNXbs"
                + "&Signature=BSuAgonY3WhDiEroH4FW8A4A%2Fl0%3D";

        String savePath = "downloaded_image.png"; // 保存路径

        try {
            downloadImage(ossUrl, savePath);
            System.out.println("图片下载成功，保存至: " + savePath);
        } catch (IOException e) {
            System.err.println("下载失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void downloadImage(String fileUrl, String savePath) throws IOException {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        FileOutputStream outputStream = null;

        try {
            // 1. 创建HTTP连接
            URL url = new URL(fileUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 2. 设置请求头（模拟浏览器访问）
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");

            // 3. 验证响应状态
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new IOException("服务器返回异常状态码: " + responseCode);
            }

            // 4. 获取输入流
            inputStream = connection.getInputStream();

            // 5. 创建输出文件
            outputStream = new FileOutputStream(savePath);

            // 6. 缓冲区传输数据
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

        } finally {
            // 7. 关闭资源
            if (inputStream != null) inputStream.close();
            if (outputStream != null) outputStream.close();
            if (connection != null) connection.disconnect();
        }
    }
}